<?php
header("Content-Type:text/html;charset=utf-8");
class WebServer {
    protected $host;
    protected $port;
    protected $dispatcher;
    protected $request;

    public function __construct($host, $port) {
        $this->host       = $host;
        $this->port       = $port;
        $this->dispatcher = new Dispatcher();
        $this->request    = null;
    }

    public function run() {
        $s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_set_option($s, SOL_SOCKET, SO_REUSEADDR, 1);
        socket_bind($s, $this->host, $this->port);
        socket_listen($s, 10);
        while (true) {
            $readArr        = array($s);
            $changed_socket = @socket_select($readArr, $write = NULL, $except = NULL, 0);
            if ($changed_socket === false) {
                continue;
            } elseif ($changed_socket > 0) {
                $v           = socket_accept($s);
                $raw_request = socket_read($v, 1024);
                //解析请求数据
                $request = new Request($raw_request);
                //分发处理
                $this->request = $this->dispatcher->dispatch($request);
                //组装response
                $response        = new Response($this->request);
                $response_result = $response->generate_response();
                socket_write($v, $response_result);
                socket_close($v);
            }
        }
    }
}
